/*
 * 
 * ******Capture Main Activity***********************
 ******* 1)Sync Word details to server***************
 ******* 2)Sync Phrase details to server*************
 ******* 3)Sync Songs details to server**************
 ******* 4)Sync Story details to server**************
 ******* 5)Sync Idiom details to server**************
 ****************************************************/

package com.maori.languageapp;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
//import com.maori.languageapp.adapter.LanguageAppDialetDataList;
import com.maori.languageapp.adapter.Maori_NavDrawerListAdapter;
import com.maori.languageapp.consts.CaptureFilterAdapter;
import com.maori.languageapp.consts.UrlContant;
//import com.maori.languageapp.discover.Maori_Discover_Word_Details;
import com.maori.languageapp.fragments.Maori_Main_Fragment;
import com.maori.languageapp.model.Maori_NavDrawerItem;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.VideoView;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

@SuppressLint("NewApi") @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public class LanguageAppCaptureModify extends FragmentActivity {
	// private PBDatabaseAdapter dbHelper;
	ProgressDialog mProgressDialog;
	HttpParams httpParameters = new BasicHttpParams();
	int timeoutConnection = 5000;
	int NCMID;
    String MID;
	String node_category = "Common", CurrentCategory, node_category_id;
	String type;
	public FTPClient mFTPClient = null;
	// Capture Word Data Insert Block
	EditText etmaoriword, etenglishword, searchfiltertext;
	// Capture Story Data Insert Block
	EditText etmaoristorytitle, etmaoristorycontent, etenglishstorytitle,
			etenglishstorycontent;
	// Capture Songs Data Insert Block
	EditText etmaorisongstitle, etmaorisongscontent, etenglishsongstitle,
			etenglishsongscontent;
	// Capture Phrase Data Insert Block
	EditText etmaoriphrase, etenglishphrase;
	// Capture Idiom Data Insert Block
	EditText etmaoriidiom, etenglishidiom;
	// Common Data insert block
	EditText etvideourl;
	private Uri fileUri;
	Button record_button, play_button, camera_button, gallery_button,
			submitbtn, cancelbtn, videorecord_button, videorecordplay_button,
			btnsearchstart, btnsearchclose;
	String CurrentUID,CurrentUserName,MainNodeDetails,UpdateNID;
	InputStream is = null;
	StringBuilder sb = null;
	String result = null;
	private MediaRecorder myRecorder;
	int recordActive = 0;
	int recordPlay = 0;
	int recordPlayVideo = 0;
	String CurrentContentType = "0";
	private MediaPlayer myPlayer;
	private String outputFile = null;
	ImageView ivThumbnailPhoto;
	ListView rdgrp;

	private CaptureFilterAdapter dbHelper;
	private SimpleCursorAdapter dataAdapter;

	// Camera Capture Action Constants
	// Data uploading
	String desDirectory = "http://langapp.testarea.co.nz:2082/lanappimage/";
	private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
	private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;

	final static int REQUEST_VIDEO_CAPTURED = 3000;
	Uri uriVideo = null;
	// directory name to store captured images and videos
	private static final String IMAGE_DIRECTORY_NAME = "lANGUAGEAPP";
	
	// ---------------------------------------------------
	VideoView videoPreview;
	int dialectidhere;
	Bitmap bitMap;
	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	private String[] navMenuTitles;
	private TypedArray navMenuIcons;
	private ArrayList<Maori_NavDrawerItem> navDrawerItems;
	private Maori_NavDrawerListAdapter adapter;
	String CurrentTypeOfCapture, content_type_id;
	private Spinner spinnerTypeOfCapture, spinnerCategory;
	private ArrayAdapter<CharSequence> m_adapterForSpinnerTC;
	private ArrayAdapter<CharSequence> m_adapterForSpinnerCat;
	private static final int PICK_IMAGE = 1;
	// Database Name
	private static final String DATABASE_NAME = "maorilanguageapp.db";
	protected static final String TAG = null;
	// Master Tables
	private String USER_TABLE = "User";
	private String CONTENTTYPE_TABLE = "Content_type";
	private String DIALACT_TABLE = "Dialact";
	private String LANGUAGE_TABLE = "Language";
	private String MEDIA_TABLE = "Media";
	private String NODECATEGORY_TABLE = "Node_Category";
	private String PHRASE_TABLE = "Phrase";
	private String SONG_TABLE = "Song";
	private String STORY_TABLE = "Story";
	private String WORD_TABLE = "Word";

	// Save Image,Audio Video Paths
	private String MEDIA_FILE_URL = "MediaFileUrl";

	private SQLiteDatabase mydb;
	int DialetPasition;
	private RadioButton listRadioButton = null;
	int listIndex = -1;
	private ListView listView;
	//private List<LanguageAppDialetDataList> rowItems;
	//LanguageAppDialetDataList DialetListData;
	//LanguageAppDialetAdapterList DialectAdapter;
	private static int RESULT_LOAD_IMAGE = 1;
	Uri selectedImageUri;
	byte[] data;
	String filemanagerstring;
	String selectedImagePath;
	String filePath;
	private Bitmap bitmap;
	LinearLayout capturewordblock, capturestoryblock, capturesongsblock,
			capturephraseblock, captureidiomblock, dmstloadmaindetails,
			searchlistresult, camvideoparent;
	private String tempDir;
	String currentImageName = "1";
	String currentAudioName = "202";
	String currentVideoName = "303";
	static String filename = "404";

	String saveWordDetailsUrl, savePhraseDetailsUrl, saveStoryDetailsUrl,
			saveIdiomDetailsUrl, saveSongDetailsUrl;
	
	String updateSaveWordDetailsUrl;
	static String upladingFromPath, sourceUrl;

	private String servernameimages = "ftp.langapp.testarea.co.nz";
	private String servusername = "images@langapp.testarea.co.nz";
	private String passworsd = "languageapp@237";
	private int portnum = 21;

	ListView listViewitemslist;

	// Media resource path
	String AudioMainPath;

	@SuppressLint("NewApi") @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.language_app_capture_activity);
		// PSJ - Code To Add Drawer

		getCurrentUserDetails();
		dbHelper = new CaptureFilterAdapter(this);
		dbHelper.open();
		mTitle = mDrawerTitle = getTitle();

		// Capture Web service Call Defines
		saveWordDetailsUrl = UrlContant.SaveWordUrl;
		savePhraseDetailsUrl = UrlContant.SavePhraseUrl;
		saveStoryDetailsUrl = UrlContant.SaveStoryUrl;
		saveIdiomDetailsUrl = UrlContant.SaveIdiomUrl;
		saveSongDetailsUrl = UrlContant.SaveSongUrl;

		updateSaveWordDetailsUrl = UrlContant.UpdateSaveWordUrl;
		
		
		navMenuTitles = getResources().getStringArray(
				R.array.maori_nav_drawer_items);

		navMenuIcons = getResources().obtainTypedArray(
				R.array.maori_nav_drawer_icons);

		listViewitemslist = (ListView) findViewById(R.id.listViewitemslist);

		/**************************************************************************
		 * *******Search Excisting Filter Option*************
		 * ************************************************************************/
		btnsearchstart = (Button) findViewById(R.id.btnsearchstart);

		dmstloadmaindetails = (LinearLayout) findViewById(R.id.dmstloadmaindetails);
		searchlistresult = (LinearLayout) findViewById(R.id.searchlistresult);
		camvideoparent = (LinearLayout) findViewById(R.id.camvideoparent);
		
		/*cancelbtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				displayCancelDialog();
			}
		});*/

		
		btnsearchstart.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				if (type.equals("Word")) {
					Log.v(TAG, "****** Word *******");
					Intent i = new Intent(getApplicationContext(),
							LanguageAppSearchArea.class);
					i.putExtra("NCMID", NCMID);
					i.putExtra("node_category", node_category);
					i.putExtra("type", "Word");
					startActivity(i);
				} else if (type.equals("Phrase")) {
					Log.v(TAG, "****** Phrase *******");
					Intent i = new Intent(getApplicationContext(),
							LanguageAppSearchArea.class);
					i.putExtra("NCMID", NCMID);
					i.putExtra("node_category", node_category);
					i.putExtra("type", "Phrase");
					startActivity(i);

				} else if (type.equals("Story")) {
					Log.v(TAG, "****** Story *******");
					Intent i = new Intent(getApplicationContext(),
							LanguageAppSearchArea.class);
					i.putExtra("NCMID", NCMID);
					i.putExtra("node_category", node_category);
					i.putExtra("type", "Story");
					startActivity(i);

				} else if (type.equals("Idiom")) {
					Log.v(TAG, "****** Idiom *******");
					Intent i = new Intent(getApplicationContext(),
							LanguageAppSearchArea.class);
					i.putExtra("NCMID", NCMID);
					i.putExtra("node_category", node_category);
					i.putExtra("type", "Idiom");
					startActivity(i);

				} else if (type.equals("Song")) {
					Log.v(TAG, "****** Song *******");
					Intent i = new Intent(getApplicationContext(),
							LanguageAppSearchArea.class);
					i.putExtra("NCMID", NCMID);
					i.putExtra("node_category", node_category);
					i.putExtra("type", "Song");
					startActivity(i);
				}
			}
		});

		/******************** Fileter Excisting END ****************************/

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout_cap_word);
		mDrawerList = (ListView) findViewById(R.id.list_slidermenu_cap_word);

		navDrawerItems = new ArrayList<Maori_NavDrawerItem>();

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[0],
				navMenuIcons.getResourceId(0, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[1],
				navMenuIcons.getResourceId(1, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[2],
				navMenuIcons.getResourceId(2, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[3],
				navMenuIcons.getResourceId(3, -1), true, "22"));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[4],
				navMenuIcons.getResourceId(4, -1)));

		navDrawerItems.add(new Maori_NavDrawerItem(navMenuTitles[5],
				navMenuIcons.getResourceId(5, -1), true, "50+"));

		navMenuIcons.recycle();

		mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

		adapter = new Maori_NavDrawerListAdapter(getApplicationContext(),
				navDrawerItems);
		mDrawerList.setAdapter(adapter);

		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setBackgroundDrawable(
				new ColorDrawable(Color.parseColor("#0d284c")));

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.menubutton, R.string.app_name, R.string.app_name) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu();
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			UpdateNID = extras.getString("UpdateNID");
			MainNodeDetails = extras.getString("MainNodeDetails");
			type = extras.getString("type");
			MID = extras.getString("MID");
			Log.v(TAG, "***type***:"+ type);
			Log.v(TAG, "***UpdateNID***:"+ UpdateNID);
			Log.v(TAG, "***MainNodeDetails***:"+ MainNodeDetails);
		}
		capturewordblock = (LinearLayout) findViewById(R.id.capturewordblock);
		capturestoryblock = (LinearLayout) findViewById(R.id.capturestoryblock);
		capturesongsblock = (LinearLayout) findViewById(R.id.capturesongsblock);
		capturephraseblock = (LinearLayout) findViewById(R.id.capturephraseblock);
		captureidiomblock = (LinearLayout) findViewById(R.id.captureidiomblock);
		// ****Define Main Type Capture Blocks****
		Log.v(TAG, "PRINT TYPE : " + type);
		if (type.equals("Word")) {
			capturewordblock.setVisibility(LinearLayout.VISIBLE);
		} else if (type.equals("Phrase")) {
			capturephraseblock.setVisibility(LinearLayout.VISIBLE);
		} else if (type.equals("Story")) {
			capturestoryblock.setVisibility(LinearLayout.VISIBLE);
		} else if (type.equals("Idiom")) {
			captureidiomblock.setVisibility(LinearLayout.VISIBLE);
		} else if (type.equals("Song")) {
			capturesongsblock.setVisibility(LinearLayout.VISIBLE);
		}

		EditText EtType = (EditText) findViewById(R.id.ettypeofcapture);
		EditText EtCat = (EditText) findViewById(R.id.etselectcategory);

		// Get Values From EditText Values(Word)
		etmaoriword = (EditText) findViewById(R.id.etmaoriword);
		etenglishword = (EditText) findViewById(R.id.etenglishword);
		// Get Values From EditText Values(Story)
		etmaoristorytitle = (EditText) findViewById(R.id.etmaoristorytitle);
		etmaoristorycontent = (EditText) findViewById(R.id.etmaoristorycontent);
		etenglishstorytitle = (EditText) findViewById(R.id.etenglishstorytitle);
		etenglishstorycontent = (EditText) findViewById(R.id.etenglishstorycontent);
		searchfiltertext = (EditText) findViewById(R.id.searchfiltertext);

		// Get Values From EditText Values(Songs)
		etmaorisongstitle = (EditText) findViewById(R.id.etmaorisongstitle);
		etmaorisongscontent = (EditText) findViewById(R.id.etmaorisongscontent);
		etenglishsongstitle = (EditText) findViewById(R.id.etenglishsongstitle);
		etenglishsongscontent = (EditText) findViewById(R.id.etenglishsongscontent);
		// Get Values From EditText Values(Phrase)
		etmaoriphrase = (EditText) findViewById(R.id.etmaoriphrase);
		etenglishphrase = (EditText) findViewById(R.id.etenglishphrase);
		// Get Values From EditText Values(Idiom)
		etmaoriidiom = (EditText) findViewById(R.id.etmaoriidiom);
		etenglishidiom = (EditText) findViewById(R.id.etenglishidiom);

		etvideourl = (EditText) findViewById(R.id.etvideourl);

		// Button View Controllers
		record_button = (Button) findViewById(R.id.record_button);
		play_button = (Button) findViewById(R.id.play_button);
		camera_button = (Button) findViewById(R.id.camera_button);
		gallery_button = (Button) findViewById(R.id.gallery_button);
		videorecord_button = (Button) findViewById(R.id.videorecord_button);
		videorecordplay_button = (Button) findViewById(R.id.videorecordplay_button);

		videoPreview = (VideoView) findViewById(R.id.videoview);
		// Submit Word Details To Server
		submitbtn = (Button) findViewById(R.id.submitbtn);
		submitbtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				new UploadingWordsDetails().execute();
			}
		});

		// Cancel Current View and Exit
		cancelbtn = (Button) findViewById(R.id.cancelbtn);
		cancelbtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				displayCancelDialog();
			}
		});

		// ***** Recording Audio Function
		record_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				if (recordActive == 0) {
					recordActive = 1;
					// Audio Recording
					// store it to sd card
					record_button.setBackground(getResources().getDrawable(
							R.drawable.recordstop_button));
					outputFile = Environment.getExternalStorageDirectory()
							.getAbsolutePath()
							+ "/"
							+ getAudiorecording().toString() + ".mp4";
					AudioMainPath = Environment.getExternalStorageDirectory()
							.getAbsolutePath() + "/";
					currentAudioName = getAudiorecording().toString() + ".mp4";
					myRecorder = new MediaRecorder();
					myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
					myRecorder
							.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
					myRecorder
							.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
					myRecorder.setOutputFile(outputFile);
					Log.v(TAG, "AUDIO PATH : " + currentAudioName);
					saveMediaFileDetails();
					play_button.setEnabled(false);
					start(view);
				} else if (recordActive == 1) {
					recordActive = 0;
					record_button.setBackground(getResources().getDrawable(
							R.drawable.record_button));
					play_button.setEnabled(true);
					stop(view);
				}

			}
		});

		// Play Current Recoring
		play_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (recordPlay == 0) {
					recordPlay = 1;
					play_button.setBackground(getResources().getDrawable(
							R.drawable.playstop_button));
					record_button.setEnabled(false);
					recordPlay(view);
				} else if (recordPlay == 1) {
					recordPlay = 0;
					play_button.setBackground(getResources().getDrawable(
							R.drawable.play_button));
					record_button.setEnabled(true);
					stopPlay(view);
				}

			}
		});

		// Launch Camera
		ivThumbnailPhoto = (ImageView) findViewById(R.id.ImageView01);
		camera_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// create intent with ACTION_IMAGE_CAPTURE action
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

				Log.v(TAG, "PRINT _ 1: " + fileUri);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
				// start the image capture Intent
				startActivityForResult(intent,
						CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
			}
		});

		gallery_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				try {
					Intent intent = new Intent();
					intent.setType("image/*");
					intent.setAction(Intent.ACTION_GET_CONTENT);
					startActivityForResult(
							Intent.createChooser(intent, "Select Picture"),
							PICK_IMAGE);

				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), e.getMessage(),
							Toast.LENGTH_LONG).show();
					Log.e(e.getClass().getName(), e.getMessage(), e);
				}

			}
		});

		videorecord_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
			
				fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
				String URIPATH = fileUri.toString();
				String[] separated = URIPATH.split("/");
				currentVideoName = separated[8];
				Log.v(TAG, "VIDEO PRINT URI : " + currentVideoName);
// file:///storage/emulated/0/Pictures/lANGUAGEAPP/VID_20140421_133732.mp4
				// set video quality
				intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

				intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the
																	// image
																	// file
																	// name
				openPath(fileUri);
				
				
				
				videoPreview.setVisibility(View.VISIBLE);
				// start the video capture Intent
				startActivityForResult(intent,
						CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
			}
		});

		// Play Current Recoring
		videorecordplay_button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				if (uriVideo == null) {
					Toast.makeText(LanguageAppCaptureModify.this, "No Video",
							Toast.LENGTH_LONG).show();
				} else {
					if (recordPlayVideo == 0) {
						Toast.makeText(LanguageAppCaptureModify.this,
								"Playback: " + uriVideo.getPath(),
								Toast.LENGTH_LONG).show();
						videorecordplay_button.setBackground(getResources()
								.getDrawable(R.drawable.playstop_button));
						videorecord_button.setEnabled(false);
						videoPreview.setVideoURI(uriVideo);
						videoPreview.start();
					} else if (recordPlayVideo == 1) {
						recordPlayVideo = 0;
						videorecordplay_button.setBackground(getResources()
								.getDrawable(R.drawable.play_button));
						videorecord_button.setEnabled(true);
						stopPlayVideo(view);
					}
				}
			}
		});
		// Video recording Function gallery_button,audiorecord_button

		spinnerTypeOfCapture = (Spinner) findViewById(R.id.spinnerTypeOfCapture);
		spinnerCategory = (Spinner) findViewById(R.id.spinnerCategory);
		loadTypeOfCapture();
		loadCategory();

		// Spinner List Handling Activities
		spinnerTypeOfCapture.setAdapter(m_adapterForSpinnerTC);
		spinnerTypeOfCapture
				.setOnItemSelectedListener(new OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						CurrentTypeOfCapture = spinnerTypeOfCapture
								.getSelectedItem().toString();
						if (!(CurrentTypeOfCapture.equals("SELECT SERVER DB"))) {

							mydb = openOrCreateDatabase(DATABASE_NAME,
									Context.MODE_PRIVATE, null);

							Cursor getfromloccur = null;
							try {
								getfromloccur = mydb.query(CONTENTTYPE_TABLE,
										null, "content='"
												+ CurrentTypeOfCapture + "'",
										null, null, null, null, null);
							} catch (Exception e) {

							}
							if (getfromloccur != null) {
								if (getfromloccur.getCount() > 0) {
									while (getfromloccur.moveToNext()) {
										content_type_id = getfromloccur
												.getString(1);
										type = getfromloccur.getString(2);
										if (type.equals("Word")) {
											capturewordblock
													.setVisibility(LinearLayout.VISIBLE);
											capturephraseblock
													.setVisibility(LinearLayout.GONE);
											capturestoryblock
													.setVisibility(LinearLayout.GONE);
											captureidiomblock
													.setVisibility(LinearLayout.GONE);
											capturesongsblock
													.setVisibility(LinearLayout.GONE);
										} else if (type.equals("Phrase")) {
											capturephraseblock
													.setVisibility(LinearLayout.VISIBLE);
											capturewordblock
													.setVisibility(LinearLayout.GONE);
											capturestoryblock
													.setVisibility(LinearLayout.GONE);
											captureidiomblock
													.setVisibility(LinearLayout.GONE);
											capturesongsblock
													.setVisibility(LinearLayout.GONE);
										} else if (type.equals("Story")) {
											capturestoryblock
													.setVisibility(LinearLayout.VISIBLE);
											capturewordblock
													.setVisibility(LinearLayout.GONE);
											capturephraseblock
													.setVisibility(LinearLayout.GONE);
											captureidiomblock
													.setVisibility(LinearLayout.GONE);
											capturesongsblock
													.setVisibility(LinearLayout.GONE);
										} else if (type.equals("Idiom")) {
											captureidiomblock
													.setVisibility(LinearLayout.VISIBLE);
											capturestoryblock
													.setVisibility(LinearLayout.GONE);
											capturewordblock
													.setVisibility(LinearLayout.GONE);
											capturephraseblock
													.setVisibility(LinearLayout.GONE);
											capturesongsblock
													.setVisibility(LinearLayout.GONE);
										} else if (type.equals("Song")) {
											capturesongsblock
													.setVisibility(LinearLayout.VISIBLE);
											captureidiomblock
													.setVisibility(LinearLayout.GONE);
											capturestoryblock
													.setVisibility(LinearLayout.GONE);
											capturewordblock
													.setVisibility(LinearLayout.GONE);
											capturephraseblock
													.setVisibility(LinearLayout.GONE);
										}

										Log.v(TAG, "Capture :"
												+ content_type_id + " = "
												+ type);
									}
								}
								getfromloccur.close();
							}

						} else {
						}

					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});

		spinnerCategory.setAdapter(m_adapterForSpinnerCat);
		spinnerCategory.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				CurrentCategory = spinnerCategory.getSelectedItem().toString();
				if (!(CurrentCategory.equals("SELECT SERVER DB"))) {

					SQLiteDatabase mydb;
					mydb = openOrCreateDatabase(DATABASE_NAME,
							Context.MODE_PRIVATE, null);

					Cursor getFromCategory = null;
					try {
						getFromCategory = mydb.query(NODECATEGORY_TABLE, null,
								"node_category='" + CurrentCategory + "'",
								null, null, null, null, null);
					} catch (Exception e) {

					}
					if (getFromCategory != null) {
						if (getFromCategory.getCount() > 0) {
							while (getFromCategory.moveToNext()) {
								node_category_id = getFromCategory.getString(1);
								node_category = getFromCategory.getString(2);
								Log.v(TAG, "Category :" + node_category_id
										+ " = " + node_category);
							}
						}
						getFromCategory.close();
					}
				} else {
				}

			}

			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
	}

	private void getCurrentUserDetails() {
			// TODO Auto-generated method stub
			mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
			Cursor device_user = null;
			try {
				String query = "SELECT * FROM User";
				device_user = mydb.rawQuery(query, null);
			} catch (Exception e) {
			}

			if (device_user != null) {
				if (device_user.getCount() > 0) {
					while (device_user.moveToNext()) {
						CurrentUID = device_user.getString(11);
					}
				}
			}
	}

	protected void saveMediaFileDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		ContentValues enterFileUrl = new ContentValues();
		// Check Previous Language
		Cursor enterFileUrlDetails = null;
		try {
			enterFileUrlDetails = mydb.query(MEDIA_FILE_URL, null,
					"UploadingState !='0'", null, null, null, null);
		} catch (Exception e) {
		}
		if (enterFileUrlDetails != null) {
			if (enterFileUrlDetails.getCount() >= 1) {
				Log.v(TAG, "Excisting Language");
			} else {
				enterFileUrl.put("McategoryId", currentAudioName);
				enterFileUrl.put("MediaFileName", currentAudioName);
				enterFileUrl.put("ResouceDeviceUrl", AudioMainPath);
				enterFileUrl.put("ResouceServerUrl", AudioMainPath);
				enterFileUrl.put("UploadingState", "0");

				mydb.insert(MEDIA_FILE_URL, null, enterFileUrl);
				enterFileUrlDetails.close();
				mydb.close();
			}
		}

	}

	protected void stopPlayVideo(View view) {
		// TODO Auto-generated method stub

	}

	
	public void onRadioButtonClicked(View view) {
		// Is the button now checked?
		boolean checked = ((RadioButton) view).isChecked();
		Toast toast = new Toast(getApplicationContext());
		toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
		toast.setDuration(Toast.LENGTH_LONG);
		toast.setText("RADIO CLICK :" + checked);
		toast.show();
	}

	private void loadCategory() {
		// TODO Auto-generated method stub
		m_adapterForSpinnerCat = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item);
		m_adapterForSpinnerCat
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor curNodeCategory = null;
		try {
			curNodeCategory = mydb.query(NODECATEGORY_TABLE, null, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (curNodeCategory != null) {
			if (curNodeCategory.getCount() > 0) {
				m_adapterForSpinnerCat.add(node_category);
				while (curNodeCategory.moveToNext()) {
					m_adapterForSpinnerCat.add(curNodeCategory.getString(2));
				}
			}
			curNodeCategory.close();
		}
		mydb.close();
	}

	private void loadTypeOfCapture() {
		// TODO Auto-generated method stub
		m_adapterForSpinnerTC = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item);
		m_adapterForSpinnerTC
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		Cursor curContentType = null;
		try {
			curContentType = mydb.query(CONTENTTYPE_TABLE, null, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (curContentType != null) {
			if (curContentType.getCount() > 0) {
				m_adapterForSpinnerTC.add(type);
				while (curContentType.moveToNext()) {
					m_adapterForSpinnerTC.add(curContentType.getString(2));
				}
			}
			curContentType.close();
		}
		mydb.close();
	}

	protected void stopPlay(View view) {
		// TODO Auto-generated method stub
		try {
			if (myPlayer != null) {
				myPlayer.stop();
				myPlayer.release();
				myPlayer = null;
				Toast.makeText(getApplicationContext(),
						"Stop playing the recording...", Toast.LENGTH_SHORT)
						.show();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// Play Current Audio
	protected void recordPlay(View view) {
		// TODO Auto-generated method stub
		try {
			myPlayer = new MediaPlayer();
			myPlayer.setDataSource(outputFile);
			myPlayer.prepare();
			myPlayer.start();
			Toast.makeText(getApplicationContext(),
					"Start play the recording..." + outputFile.toString(),
					Toast.LENGTH_SHORT).show();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// Stop Playing Audio
	protected void stop(View view) {
		// TODO Auto-generated method stub
		try {
			myRecorder.stop();
			myRecorder.release();
			myRecorder = null;
			Toast.makeText(getApplicationContext(), "Stop recording...",
					Toast.LENGTH_SHORT).show();
		} catch (IllegalStateException e) {
			// it is called before start()
			e.printStackTrace();
		} catch (RuntimeException e) {
			// no valid audio/video data has been received
			e.printStackTrace();
		}
	}

	// Start Playing Audio
	protected void start(View view) {
		// TODO Auto-generated method stub
		try {
			myRecorder.prepare();
			myRecorder.start();
			Toast.makeText(getApplicationContext(), "Start recording...",
					Toast.LENGTH_SHORT).show();
		} catch (IllegalStateException e) {
			// start:it is called before prepare()
			// prepare: it is called after start() or before setOutputFormat()
			e.printStackTrace();
		} catch (IOException e) {
			// prepare() fails
			e.printStackTrace();
		}
		/*
		 * startBtn.setEnabled(false); stopBtn.setEnabled(true);
		 */
	}

	protected void displayCancelDialog() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(
				LanguageAppCaptureModify.this);
		builder.setTitle("CANCEL");
		builder.setMessage("Are Sure You Want To Exit...");
		builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				Intent myIntent = new Intent(getBaseContext(),
						Maori_MainActivity.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
			}
		});
		builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(),
						"Add New Words Details..", Toast.LENGTH_LONG).show();
			}
		});
		builder.show();
	}

	// ****Data uploading background service
	private class UploadingWordsDetails extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(
					LanguageAppCaptureModify.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading " + type + " Details");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				if (type.equals("Word")) {
					CurrentContentType = "1";
					httppost = new HttpPost(updateSaveWordDetailsUrl);//saveWordDetailsUrl
				} else if (type.equals("Phrase")) {
					CurrentContentType = "2";
					httppost = new HttpPost(savePhraseDetailsUrl);
				} else if (type.equals("Story")) {
					CurrentContentType = "3";
					httppost = new HttpPost(saveStoryDetailsUrl);
					Log.v(TAG, "SAVE STORY : " + saveStoryDetailsUrl);
				} else if (type.equals("Idiom")) {
					CurrentContentType = "5";
					httppost = new HttpPost(saveIdiomDetailsUrl);
				} else if (type.equals("Song")) {
					CurrentContentType = "4";
					httppost = new HttpPost(saveSongDetailsUrl);
					Log.v(TAG, "SAVE SONGS : " + saveSongDetailsUrl);
				}
				Log.v(TAG, "CurrentUID 9999 : " + CurrentUID);
				JSONObject json = new JSONObject();
				// Selected Type ID
				json.put("record1", CurrentContentType);
				// Added User ID
				json.put("record2", CurrentUID);
				// Record Added Date
				json.put("record3", getAddDateTimeString().toString());
				// Uploading user id
				json.put("record4", CurrentUID);
				// Record Updated
				json.put("record5", getAddDateTimeString().toString());
				// Selected dialect ID
				json.put("record6", "1");
				// Curent Node Category ID
				json.put("record7", MID);
				// Uploading Language Details
				json.put("record8", "2=1"); // LID

				if (type.equals("Word")) {
					// Uploading Word Details
					json.put("record9", etenglishword.getText().toString()
							+ "=" + etmaoriword.getText().toString()); // word
				} else if (type.equals("Phrase")) {
					// Uploading Phrase Details
					json.put("record9", etmaoriphrase.getText().toString()
							+ "=" + etenglishphrase.getText().toString()); // word
				} else if (type.equals("Idiom")) {
					// Uploading Idiom Details
					json.put("record9", etenglishidiom.getText().toString()
							+ "=" + etmaoriidiom.getText().toString()); // word
				} else if (type.equals("Song")) {
					// etmaorisongstitle,etmaorisongscontent,etenglishsongstitle,etenglishsongscontent
					json.put("recordt9", etenglishsongstitle.getText()
							.toString()
							+ "="
							+ etmaorisongstitle.getText().toString()); // word
					json.put("record9", etenglishsongscontent.getText()
							.toString()
							+ "="
							+ etmaorisongscontent.getText().toString()); // word
					Log.v(TAG, "SAVE SONGS");
				} else if (type.equals("Story")) {
					// etmaoristorytitle/etmaoristorycontent/etenglishstorytitle/etenglishstorycontent
					json.put("recordt9", etenglishstorytitle.getText()
							.toString()
							+ "="
							+ etmaoristorytitle.getText().toString()); // word
					json.put("record9", etenglishstorycontent.getText()
							.toString()
							+ "="
							+ etmaoristorycontent.getText().toString()); // word
					Log.v(TAG, "SAVE STORY");
				}
				/*String currentAudioName = "202";
				String currentVideoName = "303";
				static String filename = "404";*/
				// uploading image name
				if(filename.equals("404")){
					json.put("record10", filename);
				}
				else{
					json.put("record10", "1="+ "http://langapp.mirzabros.com/lanappimage/"+ filename);
				}
				// uploading audio name
				if(currentAudioName.equals("202")){
					json.put("record11", "2="+ currentAudioName);
				}
				else{
					json.put("record11", "2="+ "http://langapp.mirzabros.com/lanappaudio/"+ currentAudioName);
				}
				// uploading video name
				if(currentVideoName.equals("303")){
					json.put("record12", "3="+ currentVideoName);
				}
				else{
					json.put("record12", "3="+ "http://langapp.mirzabros.com/lanappvideo/"+ currentVideoName);
				}
				// Uploading url details
				json.put("record13", etvideourl.getText().toString());
				json.put("record14", "6");
				json.put("record15", UpdateNID);
				
				JSONArray postjson = new JSONArray();
				postjson.put(json);

				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				Log.e("postjson", "postjson :" + postjson.toString());

				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					if (result != null) {

					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();

			if (isNetworkAvailable()) {
				new UploadTask().execute();
				
			} else {
				AlertDialog.Builder b = new AlertDialog.Builder(
						LanguageAppCaptureModify.this);
				b.setMessage("Internet connectivity failure.Try again!");
				b.show();
			}

		}

	}

	private class SlideMenuClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			LinearLayout lnlar = (LinearLayout) findViewById(R.id.cap_word_linear);
			lnlar.setVisibility(View.GONE);
			displayView(position);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);

		MenuItem searchItem = menu.findItem(R.id.search);
		SearchView searchView = (SearchView) MenuItemCompat
				.getActionView(searchItem);

		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {

		boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	private void displayView(int position) {
		Fragment fragment = null;
		switch (position) {
		case 0:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 1:
			fragment = new Maori_Main_Fragment(1);
			break;
		case 2:
			fragment = new Maori_Main_Fragment(2);
			break;
		case 3:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 4:
			fragment = new Maori_Main_Fragment(0);
			break;
		case 5:
			fragment = new Maori_Main_Fragment(0);
			break;

		default:
			break;
		}

		if (fragment != null) {
			FragmentManager fragmentManager = getSupportFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.frame_container_cap_word, fragment).commit();

			mDrawerList.setItemChecked(position, true);
			mDrawerList.setSelection(position);
			setTitle(navMenuTitles[position]);
			mDrawerLayout.closeDrawer(mDrawerList);
		} else {
			Log.e("MainActivity", "Error in creating fragment");
		}
	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getActionBar().setTitle(mTitle);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	private String getAddDateTimeString() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	private String getAudiorecording() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("yyyyMMddHHmmss");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	public void onBackPressed() {
		super.onBackPressed();
	}

	/**
	 * Receiving activity result method will be called after closing the camera
	 * */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// if the result is capturing Image
		if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				// successfully captured the image
				// display it in image view
				previewCapturedImage();
			} else if (resultCode == RESULT_CANCELED) {
				// user cancelled Image capture
				Toast.makeText(getApplicationContext(),
						"User cancelled image capture", Toast.LENGTH_SHORT)
						.show();
			} else {
				// failed to capture image
				Toast.makeText(getApplicationContext(),
						"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
						.show();
			}
		} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
			camvideoparent.setVisibility(View.VISIBLE);
			if (resultCode == RESULT_OK) {
				// video successfully recorded
				// preview the recorded video
				camvideoparent.setVisibility(View.VISIBLE);
				previewVideo();
			} else if (resultCode == RESULT_CANCELED) {
				// user cancelled recording
				Toast.makeText(getApplicationContext(),
						"User cancelled video recording", Toast.LENGTH_SHORT)
						.show();
			} else {
				// failed to record video
				Toast.makeText(getApplicationContext(),
						"Sorry! Failed to record video", Toast.LENGTH_SHORT)
						.show();
			}
		}

		else if (resultCode == Activity.RESULT_OK) {
			if (resultCode == Activity.RESULT_OK) {
				selectedImageUri = data.getData();
				Log.e("Bitmap", "selectedImageUri :" + selectedImageUri);
				try {
					// OI FILE Manager
					filemanagerstring = selectedImageUri.getPath();

					// MEDIA GALLERY
					selectedImagePath = getPath(selectedImageUri);

					if (selectedImagePath != null) {
						filePath = selectedImagePath;
					} else if (filemanagerstring != null) {
						filePath = filemanagerstring;
					} else {
						Toast.makeText(getApplicationContext(), "Unknown path",
								Toast.LENGTH_LONG).show();
						Log.e("Bitmap", "Unknown path");
					}

					if (filePath != null) {
						decodeFile(filePath);
					} else {
						bitmap = null;
					}
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "Internal error",
							Toast.LENGTH_LONG).show();
					Log.e(e.getClass().getName(), e.getMessage(), e);
				}
			}
		}

	}

	private boolean prepareDirectory() {
		try {
			if (makedirs()) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(
					this,
					"Could not initiate File System.. Is Sdcard mounted properly?",
					Toast.LENGTH_SHORT).show();
			return false;
		}
	}

	private boolean makedirs() {
		File tempdir = new File(tempDir);
		if (!tempdir.exists())
			tempdir.mkdirs();

		if (tempdir.isDirectory()) {

		}
		return (tempdir.isDirectory());
	}

	private String decodeFile(String filePath) {
		// Decode image size
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, o);

		// The new size we want to scale to
		final int REQUIRED_SIZE = 1024;

		// Find the correct scale value. It should be the power of 2.
		int width_tmp = o.outWidth, height_tmp = o.outHeight;
		int scale = 1;
		while (true) {
			if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
				break;
			width_tmp /= 2;
			height_tmp /= 2;
			scale *= 2;
		}

		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize = scale;

		bitmap = BitmapFactory.decodeFile(filePath, o2);
		ivThumbnailPhoto.setImageBitmap(bitmap);

		Calendar c = Calendar.getInstance();
		SimpleDateFormat dfsigdate = new SimpleDateFormat("yyyyMMddHHmmss");
		String formattedSigDatep = dfsigdate.format(c.getTime());
		tempDir = "/data/data/com.maori.languageapp/CAMIMAGES/";
		Log.v(TAG, "XXX tempDir : " + tempDir);
		prepareDirectory();
		String filenamepath = tempDir + getAudiorecording().toString() + ".png";
		currentImageName = getAudiorecording().toString() + ".png";

		Log.v(TAG, "XXX tempDir : " + filenamepath);
		File dest = new File(filenamepath);
		try {
			FileOutputStream out = new FileOutputStream(dest);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			Log.v(TAG, "Exception : " + e);
		}

		return filePath;
	}

	private String getPath(Uri selectedImageUri) throws FileNotFoundException {

		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
				null);

		if (cursor != null) {

			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

			cursor.moveToFirst();
			/* Uri uri = Uri.parse(cursor.getString(1)); */

			return cursor.getString(column_index);
		} else
			return null;
	}

	// ====================================
	private byte[] getByteArrayFromImage(String filePath)
			throws FileNotFoundException, IOException {

		File file = new File(filePath);
		System.out.println(file.exists() + "!!");

		FileInputStream fis = new FileInputStream(file);
		// create FileInputStream which obtains input bytes from a file in a
		// file system
		// FileInputStream is meant for reading streams of raw bytes such as
		// image data. For reading streams of characters, consider using
		// FileReader.

		// InputStream in = resource.openStream();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		try {
			for (int readNum; (readNum = fis.read(buf)) != -1;) {
				bos.write(buf, 0, readNum);
				// no doubt here is 0
				/*
				 * Writes len bytes from the specified byte array starting at
				 * offset off to this byte array output stream.
				 */
				System.out.println("read " + readNum + " bytes,");
			}
		} catch (IOException ex) {
			Log.d("error", "error");
		}
		byte[] bytes = bos.toByteArray();
		return bytes;
	}

	/**
	 * ------------ Helper Methods ----------------------
	 * */

	public void openPath(Uri uri) {
		InputStream is = null;
		try {
			is = getContentResolver().openInputStream(uri);

			// Convert your stream to data here
			is.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * Creating file uri to store image/video
	 */
	public Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	/*
	 * returning image / video
	 */
	private static File getOutputMediaFile(int type) {

		// External sdcard location
		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				IMAGE_DIRECTORY_NAME);
		Log.v(TAG, "PRINT _ 4: " + mediaStorageDir);
		upladingFromPath = mediaStorageDir.getAbsolutePath();
		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
						+ IMAGE_DIRECTORY_NAME + " directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
				Locale.getDefault()).format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_" + timeStamp + ".jpg");
			filename = "IMG_" + timeStamp + ".jpg";
			sourceUrl = mediaFile.toString();
			Log.v(TAG, "PRINT _ 5: " + filename);
			Log.v(TAG, "PRINT _ 6: " + sourceUrl);

		} else if (type == MEDIA_TYPE_VIDEO) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "VID_" + timeStamp + ".mp4");
			Log.v(TAG, "PRINT _ 7: " + mediaFile);
		} else {
			return null;
		}

		return mediaFile;
	}

	/*
	 * Display image from a path to ImageView
	 */
	private void previewCapturedImage() {
		try {
			// hide video preview
			// videoPreview.setVisibility(View.GONE);

			ivThumbnailPhoto.setVisibility(View.VISIBLE);

			// bimatp factory
			BitmapFactory.Options options = new BitmapFactory.Options();

			// downsizing image as it throws OutOfMemory Exception for larger
			// images
			options.inSampleSize = 8;

			final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
					options);
			ivThumbnailPhoto.setImageBitmap(bitmap);
			Log.v(TAG, "PRINT _ PREVIEW 1 : " + fileUri.getPath());

		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}

	/*
	 * Previewing recorded video
	 */
	private void previewVideo() {
		try {
			// hide image preview
			// imgPreview.setVisibility(View.GONE);

			camvideoparent.setVisibility(View.VISIBLE);
			videoPreview.setVideoPath(fileUri.getPath());
			// start playing
			videoPreview.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// *********Media Files Uploading **************

	// ******UPLOADING BLOCK************************
	// Check Internet Connection!!!

	public boolean isNetworkAvailable() {
		ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	class UploadTask extends AsyncTask<Void, Void, Void> {

		ProgressDialog pDialog;
		Boolean uploadStat;

		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(LanguageAppCaptureModify.this);
			pDialog.setMessage("Uploading Image Files...");
			pDialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// /Pictures/lANGUAGEAPP
			upladingFromPath = "/storage/emulated/0/Pictures/lANGUAGEAPP/";
			Log.v(TAG, "data uploading 1 : " + upladingFromPath);
			Log.v(TAG, "data uploading 2 : " + filename);
			Log.v(TAG, "data uploading 3 : " + desDirectory);

			uploadStat = new UploadToFtp().ftpUpload1(upladingFromPath,
					filename, desDirectory);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (uploadStat) {
						/*final AlertDialog alertDialog = new AlertDialog.Builder(
								LanguageAppCaptureActivity.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("DATA ULOADED SUCCESS");
						// Setting Dialog Message
						alertDialog.setMessage("Data Uploading Completed...");
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										Intent myIntent = new Intent(
												getBaseContext(),
												Maori_MainActivity.class);
										myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
												| Intent.FLAG_ACTIVITY_NEW_TASK);
										startActivityForResult(myIntent, 0);
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;*/

					} else {
						AlertDialog.Builder b = new AlertDialog.Builder(
								LanguageAppCaptureModify.this);
						b.setMessage("Upload Failed.");
						b.show();
					}

				}
			});
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (null != pDialog && pDialog.isShowing()) {
				pDialog.dismiss();
			}
			super.onPostExecute(result);
			new UploadTaskAudio().execute();
		
		}
	}
	
	
	
	/**************** Uploading Audio Via FTP ************************/
	class UploadTaskAudio extends AsyncTask<Void, Void, Void> {

		ProgressDialog pDialog;
		Boolean uploadStat;

		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(LanguageAppCaptureModify.this);
			pDialog.setMessage("Uploading Audio Files...");
			pDialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// /Pictures/lANGUAGEAPP
			upladingFromPath = "/storage/emulated/0/";
			Log.v(TAG, "data uploading 1 : " + upladingFromPath);
			Log.v(TAG, "data uploading 2 : " + currentAudioName);
			Log.v(TAG, "data uploading 3 : " + desDirectory);

			uploadStat = new UploadToFtpAudio().ftpUpload1(upladingFromPath,
					currentAudioName, desDirectory);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (uploadStat) {
	
					} else {
						AlertDialog.Builder b = new AlertDialog.Builder(
								LanguageAppCaptureModify.this);
						b.setMessage("Upload Failed.");
						b.show();
					}

				}
			});
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (null != pDialog && pDialog.isShowing()) {
				pDialog.dismiss();
			}
			super.onPostExecute(result);
			new UploadTaskVideo().execute();
		}
	}

	
	/**************** Uploading Video Via FTP ************************/
	class UploadTaskVideo extends AsyncTask<Void, Void, Void> {

		ProgressDialog pDialog;
		Boolean uploadStat;

		@Override
		protected void onPreExecute() {
			pDialog = new ProgressDialog(LanguageAppCaptureModify.this);
			pDialog.setMessage("Uploading Video Files...");
			pDialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// /Pictures/lANGUAGEAPP
			upladingFromPath = "/storage/emulated/0/Pictures/lANGUAGEAPP/";
			Log.v(TAG, "data uploading 1 : " + upladingFromPath);
			Log.v(TAG, "data uploading 2 : " + currentVideoName);
			Log.v(TAG, "data uploading 3 : " + desDirectory);

			uploadStat = new UploadToFtpVideo().ftpUpload1(upladingFromPath,
					currentVideoName, desDirectory);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (uploadStat) {
	
					} else {
						AlertDialog.Builder b = new AlertDialog.Builder(
								LanguageAppCaptureModify.this);
						b.setMessage("Upload Failed.");
						b.show();
					}

				}
			});
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			if (null != pDialog && pDialog.isShowing()) {
				pDialog.dismiss();
			}
			super.onPostExecute(result);
			
			final AlertDialog alertDialog = new AlertDialog.Builder(
					LanguageAppCaptureModify.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("DATA ULOADED SUCCESS");
			// Setting Dialog Message
			alertDialog.setMessage("Data Uploading Completed...");
			// Setting OK Button
			alertDialog.setButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int which) {
							Intent myIntent = new Intent(
									getBaseContext(),
									Maori_MainActivity.class);
							myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
									| Intent.FLAG_ACTIVITY_NEW_TASK);
							startActivityForResult(myIntent, 0);
							alertDialog.dismiss();
						}
					});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}
	}

	
	//***********Memory Handling****************
	@Override
	   protected void onStop(){
	      super.onStop();
	   }

	   //Fires after the OnStop() state
	   @Override
	   protected void onDestroy() {
	      super.onDestroy();
	      try {
	         trimCache(this);
	      } catch (Exception e) {
	         // TODO Auto-generated catch block
	         e.printStackTrace();
	      }
	   }

	   public static void trimCache(Context context) {
	      try {
	         File dir = context.getCacheDir();
	         if (dir != null && dir.isDirectory()) {
	            deleteDir(dir);
	         }
	      } catch (Exception e) {
	         // TODO: handle exception
	      }
	   }

	   public static boolean deleteDir(File dir) {
	      if (dir != null && dir.isDirectory()) {
	         String[] children = dir.list();
	         for (int i = 0; i < children.length; i++) {
	            boolean success = deleteDir(new File(dir, children[i]));
	            if (!success) {
	               return false;
	            }
	         }
	      }

	      // The directory is now empty so delete it
	      return dir.delete();
	   }
}
